<template>
  <el-upload ref="upload" class="avatar-uploader" :show-file-list="false" action="http://127.0.0.1:3000/api/uploadImg"
    :onSuccess="handleAvatarChange">
    <!-- 新增时传递props.picture,这个值为一个非空的字符串,图片地址
      为新增后，服务器返回的地址 -->
    <img v-if="imgUrl && props.picture.picure" :src="imgUrl" class="avatar" />

    <!-- 编辑的时候，如果flag为真则说明，是在编辑，需要显示传过来的图片地址，编辑时
    传过来的flag为真，新增加时候传过来的为假
    editflag当上传成功后，让之前的图片不进行显示
    -->
    <!-- <img v-if="flag && editFlag" :src="`http://127.0.0.1:3000/${props.picture.picure}`" style="width: 40px" /> -->

    <span style="margin-left: 5px"> <a href="#">+点击上传</a></span>
  </el-upload>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'

import type { UploadInstance } from 'element-plus'


const props = defineProps<{
  picture: {
    picure: string
  }
  flag: boolean
}>()
console.log("77777777", props.picture.picure);
// console.log('888888888', props.flag);



const imgUrl = ref('')
// if (props.picture.picure != '') {
watch(props.picture, (a, b) => {
  console.log("aaaaaa", a);
  console.log("bbbbbb", b);

  imgUrl.value = `http://127.0.0.1:3000/${b.picure}`
})

// }

const editFlag = ref(true)
const upload = ref<UploadInstance>()
const handleAvatarChange = (e: any) => {
  // console.log(e)

  if (e.imgUrl) {
    console.log('e', e.imgUrl);

    imgUrl.value = e.imgUrl


    props.picture.picure = e.imgUrl.slice(22)
    // 当编辑的时候，让编辑这个flag为false,不显示默认的图片
    editFlag.value = false

    emit('getPicUrl', e.imgUrl.slice(22))
    // console.log('e', e.imgUrl.slice(22))
  }
}

//将获取到的图片url地址传给父组件
const emit = defineEmits<{ (e: 'getPicUrl', val: string): void }>()
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 30px;
  height: 30px;
  text-align: center;
}
</style>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 50px;
  height: 50px;
  display: block;
}

a {
  &:hover {
    text-decoration: underline;
    color: red;
    text-underline-offset: 10px;
  }

  text-decoration: none;
}
</style>
